package com.mhc.haval.controller;

import com.mhc.haval.bo.RoleBO;
import com.mhc.haval.constant.MsgCodeEnum;
import com.mhc.haval.dal.model.RoleDO;
import com.mhc.haval.form.RoleForm;
import com.mhc.haval.security.model.User;
import com.mhc.haval.service.RoleService;
import com.mhc.haval.vo.FuncVO;
import com.mhc.haval.vo.RoleFuncVO;
import com.mhc.haval.vo.RoleVO;
import com.mhc.haval.vo.StaffRoleVO;
import com.subaru.common.entity.BizResult;
import com.subaru.common.util.BeanCopierUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author Churry
 * @create 2017-08-14 11:32
 **/
@Slf4j
@RestController
@RequestMapping(value = "/roles")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 获取登录用户信息的示例
     */
    @ApiOperation(value = "获取用户信息", notes = "获取登录用户的详情信息")
    @ApiImplicitParam(name = "request", value = "http请求", required = false, dataType = "HttpServletRequest")
    @RequestMapping(value = "/staff/info", method = RequestMethod.GET)
    public Object getLogedUser(HttpServletRequest request) {
        SecurityContext securityContext = (SecurityContext) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
        Optional<SecurityContext> contextOptional = Optional.ofNullable(securityContext);
        if (contextOptional.isPresent()) {
            Object principal = securityContext.getAuthentication().getPrincipal();
            if (principal instanceof UserDetails) {
                return BizResult.create(principal, true, MsgCodeEnum.SUCCESS.getErrCode(), MsgCodeEnum.SUCCESS.getErrMsg());
            }
            return BizResult.create(MsgCodeEnum.EXCEPTION.getErrCode(), MsgCodeEnum.EXCEPTION.getErrMsg());
        } else {
            return BizResult.create(MsgCodeEnum.EXCEPTION.getErrCode(), MsgCodeEnum.EXCEPTION.getErrMsg());
        }
    }

    /**
     * 获取角色列表，不需要查询条件
     *
     * @return
     */
    @ApiOperation(value = "获取角色列表", notes = "获取角色列表的数据")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Object getRoleList() {
        //获取并返回数据
        //从数据库中取得角色do列表
        List<RoleDO> roleList = roleService.getRoleList();
        //转换成vo返回到前端
        List<RoleVO> roleVOS = new ArrayList<>();
        for (RoleDO roleDO : roleList) {
            RoleVO roleVO = BeanCopierUtil.convert(roleDO, RoleVO.class);
            roleVOS.add(roleVO);
        }
        BizResult result = BizResult.create(roleVOS, true, MsgCodeEnum.SUCCESS.getErrCode(), MsgCodeEnum.SUCCESS.getErrMsg());
        result.setTotalCount(roleVOS.size());
        return result;
    }

    /**
     * 获取角色详情的数据
     *
     * @param roleId 角色编号
     * @return
     */
    @ApiOperation(value = "获取角色详情", notes = "获取角色详情的数据")
    @ApiImplicitParam(name = "roleId", value = "角色编号", required = true, paramType = "path", dataType = "Long")
    @RequestMapping(value = "/detail/{roleId}", method = RequestMethod.GET)
    public Object getRoleDetail(@PathVariable Long roleId) {
        //获取并返回数据
        try {
            RoleVO roleVO = BeanCopierUtil.convert(roleService.getRoleDetail(roleId), RoleVO.class);
            return BizResult.create(roleVO, true, MsgCodeEnum.SUCCESS.getErrCode(), MsgCodeEnum.SUCCESS.getErrMsg());
        } catch (Exception e) {
            log.error("ERROR IN getRoleDetail", e);
            return BizResult.create(MsgCodeEnum.EXCEPTION.getErrCode(), e.getMessage());
        }
    }

    /**
     * 添加/修改一个角色
     *
     * @param roleForm 角色信息
     * @return
     */
    @ApiOperation(value = "添加/修改角色", notes = "添加/修改一个角色")
    @ApiImplicitParam(name = "roleForm", value = "角色信息", required = true, dataType = "RoleForm")
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public Object saveRoleDetail(@AuthenticationPrincipal User logedUser, @RequestBody RoleForm roleForm) {
        Optional<User> userOptional = Optional.ofNullable(logedUser);
        if (userOptional.isPresent()) {
            RoleBO roleBO = BeanCopierUtil.convert(roleForm, RoleBO.class);
            roleBO.setModifier(logedUser.getStaffId());
            //构造角色功能关联关系
            List<RoleFuncVO> roleFuncVOS = new ArrayList<>();
            for (FuncVO funcVO : roleForm.getFunList()) {
                RoleFuncVO roleFuncVO = new RoleFuncVO();
                roleFuncVO.setRoleId(roleBO.getRoleId());
                roleFuncVO.setFuncId(funcVO.getFuncId());
                roleFuncVOS.add(roleFuncVO);
            }
            Optional<Long> roleIdOptional = Optional.ofNullable(roleForm.getRoleId());
            //角色id不为空说明是更新，否则插入
            if (roleIdOptional.isPresent()) {
                roleService.updateRoleDetail(roleBO, roleFuncVOS);
            } else {
                roleService.addRoleDetail(roleBO, roleFuncVOS);
            }
            return BizResult.create(null, true, MsgCodeEnum.SUCCESS.getErrCode(), MsgCodeEnum.SUCCESS.getErrMsg());
        } else {
            return BizResult.create(MsgCodeEnum.EMPTY_USER.getErrCode(), MsgCodeEnum.EMPTY_USER.getErrMsg());
        }
    }

    /**
     * 根据角色id删除角色
     * @param roleId
     * @return
     */
    @ApiOperation(value = "根据角色id删除角色", notes = "根据角色id删除角色")
    @ApiImplicitParam(name = "roleId", value = "根据角色id删除角色", required = true, paramType = "path", dataType = "Long")
    @RequestMapping(value = "/detail/{roleId}", method = RequestMethod.DELETE)
    public Object deleteRole(@AuthenticationPrincipal User logedUser, @PathVariable Long roleId) {
        Optional<User> userOptional = Optional.ofNullable(logedUser);
        if (userOptional.isPresent()) {
            return BizResult.create(null, roleService.deleteRole(logedUser.getStaffId(), roleId), MsgCodeEnum.SUCCESS.getErrCode(), MsgCodeEnum.SUCCESS.getErrMsg());
        } else {
            return BizResult.create(MsgCodeEnum.EMPTY_USER.getErrCode(), MsgCodeEnum.EMPTY_USER.getErrMsg());
        }
    }

    /**
     * 根据角色code查找用户
     * @param logedUser
     * @param roleCode
     * @return
     */
    @ApiOperation(value = "根据角色code查找用户", notes = "根据角色code查找用户")
    @ApiImplicitParam(name = "roleCode", value = "根据角色code查找用户", required = true, paramType = "path", dataType = "String")
    @RequestMapping(value = "/selectStaffByRole/{roleCode}", method = RequestMethod.GET)
    public Object selectStaffByRole(@AuthenticationPrincipal User logedUser, @PathVariable String roleCode) {
        Optional<User> userOptional = Optional.ofNullable(logedUser);
        if (userOptional.isPresent()) {
            List<StaffRoleVO> list = roleService.selectStaffByRole(roleCode);
            return BizResult.create(list , MsgCodeEnum.SUCCESS.getErrCode(), MsgCodeEnum.SUCCESS.getErrMsg());
        } else {
            return BizResult.create(MsgCodeEnum.EMPTY_USER.getErrCode(), MsgCodeEnum.EMPTY_USER.getErrMsg());
        }
    }

}
